package org.dromara.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.json.utils.JsonUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * TRTC 转推回调控制器
 *
 * @author aaron
 */
@Slf4j
@SaIgnore
@RestController
@RequiredArgsConstructor
@RequestMapping("/trtc/callback/relay")
public class TrtcRelayCallbackController {

    /**
     * 处理转推事件回调
     *
     * @param body 回调数据
     * @return 处理结果
     */
    @PostMapping
    public R<Void> handleRelayCallback(@RequestBody String body) {
        log.info("收到TRTC转推回调: {}", body);

        try {
            Map<String, Object> callbackData = JsonUtils.parseMap(body);

            // 打印回调数据的所有字段
            log.info("=== TRTC转推回调数据开始 ===");
            for (Map.Entry<String, Object> entry : callbackData.entrySet()) {
                if (entry.getValue() instanceof Map) {
                    log.info("字段名: {}, 值类型: Map", entry.getKey());
                    Map<String, Object> nestedMap = (Map<String, Object>) entry.getValue();
                    for (Map.Entry<String, Object> nestedEntry : nestedMap.entrySet()) {
                        log.info("  - 子字段名: {}, 子字段值: {}, 子字段类型: {}",
                            nestedEntry.getKey(),
                            nestedEntry.getValue(),
                            nestedEntry.getValue() != null ? nestedEntry.getValue().getClass().getSimpleName() : "null");
                    }
                } else {
                    log.info("字段名: {}, 字段值: {}, 值类型: {}",
                        entry.getKey(),
                        entry.getValue(),
                        entry.getValue() != null ? entry.getValue().getClass().getSimpleName() : "null");
                }
            }
            log.info("=== TRTC转推回调数据结束 ===");

            Integer eventType = (Integer) callbackData.get("EventType");
            Map<String, Object> eventInfo = (Map<String, Object>) callbackData.get("EventInfo");

            switch (eventType) {
//                case "RelayStarted":
//                    handleRelayStarted(eventInfo);
//                    break;
//                case "RelayStopped":
//                    handleRelayStopped(eventInfo);
//                    break;
//                case "RelayError":
//                    handleRelayError(eventInfo);
//                    break;
                case 401:
                    handleRelayStreamStatus(eventInfo);
                    break;
                default:
                    log.warn("未知的TRTC转推回调事件类型: {}", eventType);
            }

            return R.ok();
        } catch (Exception e) {
            log.error("处理TRTC转推回调失败", e);
            return R.fail("处理转推回调失败");
        }
    }

    /**
     * 处理转推开始事件
     */
    private void handleRelayStarted(Map<String, Object> eventInfo) {
        Object roomIdObj = eventInfo.get("RoomId");
        Object taskIdObj = eventInfo.get("TaskId");
        Object streamIdObj = eventInfo.get("StreamId");
        String roomId = roomIdObj != null ? roomIdObj.toString() : null;
        String taskId = taskIdObj != null ? taskIdObj.toString() : null;
        String streamId = streamIdObj != null ? streamIdObj.toString() : null;
        log.info("转推开始: roomId={}, taskId={}, streamId={}", roomId, taskId, streamId);
        // TODO: 实现转推开始后的业务逻辑，如更新转推状态等
    }

    /**
     * 处理转推停止事件
     */
    private void handleRelayStopped(Map<String, Object> eventInfo) {
        Object roomIdObj = eventInfo.get("RoomId");
        Object taskIdObj = eventInfo.get("TaskId");
        Object streamIdObj = eventInfo.get("StreamId");
        String roomId = roomIdObj != null ? roomIdObj.toString() : null;
        String taskId = taskIdObj != null ? taskIdObj.toString() : null;
        String streamId = streamIdObj != null ? streamIdObj.toString() : null;
        log.info("转推停止: roomId={}, taskId={}, streamId={}", roomId, taskId, streamId);
        // TODO: 实现转推停止后的业务逻辑，如更新转推状态等
    }

    /**
     * 处理转推错误事件
     */
    private void handleRelayError(Map<String, Object> eventInfo) {
        Object roomIdObj = eventInfo.get("RoomId");
        Object taskIdObj = eventInfo.get("TaskId");
        Object streamIdObj = eventInfo.get("StreamId");
        Object errorCodeObj = eventInfo.get("ErrorCode");
        Object errorMessageObj = eventInfo.get("ErrorMessage");
        String roomId = roomIdObj != null ? roomIdObj.toString() : null;
        String taskId = taskIdObj != null ? taskIdObj.toString() : null;
        String streamId = streamIdObj != null ? streamIdObj.toString() : null;
        String errorCode = errorCodeObj != null ? errorCodeObj.toString() : null;
        String errorMessage = errorMessageObj != null ? errorMessageObj.toString() : null;
        log.error("转推错误: roomId={}, taskId={}, streamId={}, errorCode={}, errorMessage={}",
            roomId, taskId, streamId, errorCode, errorMessage);
        // TODO: 实现转推错误后的业务逻辑，如发送告警通知等
    }

    /**
     * 处理转推流状态事件
     */
    private void handleRelayStreamStatus(Map<String, Object> eventInfo) {
        Object roomIdObj = eventInfo.get("RoomId");
        Object taskIdObj = eventInfo.get("TaskId");
        Object streamIdObj = eventInfo.get("StreamId");
        Object statusObj = eventInfo.get("Status");
        Object bitrateObj = eventInfo.get("Bitrate");
        Object fpsObj = eventInfo.get("Fps");
        Object resolutionObj = eventInfo.get("Resolution");

        String roomId = roomIdObj != null ? roomIdObj.toString() : null;
        String taskId = taskIdObj != null ? taskIdObj.toString() : null;
        String streamId = streamIdObj != null ? streamIdObj.toString() : null;
        String status = statusObj != null ? statusObj.toString() : null;
        String bitrate = bitrateObj != null ? bitrateObj.toString() : null;
        String fps = fpsObj != null ? fpsObj.toString() : null;
        String resolution = resolutionObj != null ? resolutionObj.toString() : null;

        log.info("转推流状态: roomId={}, taskId={}, streamId={}, status={}, bitrate={}, fps={}, resolution={}",
            roomId, taskId, streamId, status, bitrate, fps, resolution);
    }
}
